;;; Guile-ZWave -- Guile talks with ZWave devices.
;;; Copyright © 2021 Ludovic Courtès <ludo@gnu.org>
;;;
;;; This file is part of Guile-ZWave.
;;;
;;; Guile-ZWave is free software; you can redistribute it and/or modify it
;;; under the terms of the GNU General Public License as published by
;;; the Free Software Foundation; either version 3 of the License, or (at
;;; your option) any later version.
;;;
;;; Guile-ZWave is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with Guile-ZWave.  If not, see <http://www.gnu.org/licenses/>.


;; This program puts the ZWave controller in "device inclusion" mode.  Once
;; it's started, you can set devices in inclusion mode as well (usually by
;; double-clicking a button on the device), and that way they'll find each
;; other.

(use-modules (zwave)
             (srfi srfi-71)
             (ice-9 match))

(define (run-device-inclusion port)
  (let ((init (initialize-zwave-state port)))
    (write-serial-message (make-request (message-class add-node-to-network)
                                        #:high-power? #f
                                        #:network-wide? #t)
                          port)
    (let loop ((state init))
      (match (select (list port) '() '())
        ((() () ())
         (loop state))
        (_
         (let* ((message (read-serial-message port))
                (notification state
                              (pop-zwave-state-notification
                               (handle-response message state))))
           (match notification
             (('inclusion-protocol-done . node)
              (format #t "inclusion process complete, total ~a nodes:~%~s~%"
                      (length (zwave-state-nodes state))
                      (zwave-state-nodes state)))
             (('included-node . node)
              (format #t "included node ~s~%" node)
              (loop state))
             (('included-controller . node)
              (format #t "included controller ~s~%" node)
              (loop state))
             (#f
              (loop state))
             ('failed
              (format #t "inclusion failed~%")
              (exit 1))
             (event
              (format #t "unknown inclusion event: ~s~%" event)
              (loop state)))))))))

(run-device-inclusion (open-zwave-serial-port (cadr (command-line))))
